package com.danceforyou.common.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;

public class HtmlToPdf {
    private static String pdfTool = "D:\\software\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";

    /**
     * html to pdf
     *
     * @param htmlSource html source,it can be local file or url
     * @param pdfFile    save to pdf file path
     * @return
     */
    public static boolean convert(String htmlSource, String pdfFile) {
        boolean result = false;
        try {
            File file = new File(pdfFile);
            File parent = file.getParentFile();
            //如果pdf保存路径不存在，则创建路径
            if (!parent.exists()) {
                parent.mkdirs();
            }

            StringBuilder cmd = new StringBuilder();
            cmd.append(pdfTool);
            cmd.append(" ");
            cmd.append(htmlSource);
            cmd.append(" ");
            cmd.append(pdfFile);

            Process proc = Runtime.getRuntime().exec(cmd.toString());
            HtmlToPdf obj = new HtmlToPdf();
            HtmlToPdfInterceptor error = obj.new HtmlToPdfInterceptor(proc.getErrorStream());
            HtmlToPdf.HtmlToPdfInterceptor output = obj.new HtmlToPdfInterceptor(proc.getInputStream());
            error.start();
            output.start();
            proc.waitFor();
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    class HtmlToPdfInterceptor extends Thread {
        private InputStream is;

        public HtmlToPdfInterceptor(InputStream is) {
            this.is = is;
        }

        public void run() {
            try {
                InputStreamReader isr = new InputStreamReader(is, "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String line = null;
                while ((line = br.readLine()) != null) {
                    System.out.println(line.toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        convert("https://mp.weixin.qq.com/s/hgoq7GMnRTliAJL_2ziMLw", "D:\\test\\mypdf.pdf");
    }
}
